package org.vacoor.ticket.handler.impl;

import java.io.UnsupportedEncodingException;

import org.vacoor.ticket.Constant;
import org.vacoor.ticket.handler.ResultHandler;
import org.vacoor.ticket.util.ParseUtil;

/**
 * 登录随机码处理器
 * @author vacoor
 *
 */
public class LoginRandCodeResultHandler implements ResultHandler<String>{

	@Override
	public String handler(byte[] content) {
		String result;
		try {
			result = new String(content,Constant.ENCODING);
		} catch (UnsupportedEncodingException e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
			result = new String(content);
		}
		return parseLoginRandCode(result);
	}
	
	/**
	 * 从返回的JSON字符串中获取登录随机码<br>
	 * JSON格式:<br>
	 * {<br>
	 * "loginRand":"439",<br>
	 * "randError":"Y" //如果该字段为Y则表示正常获取登录随机码,否则则为错误信息<br>
	 * }<br>
	 * 该方法如果randError不为Y,即获取登录随机码出错,randError为错误信息
	 * 
	 * @param randCodeJson
	 *            包含登录随机码的JSON格式字符串
	 * @return 当传入的JSON中randError值为Y时,返回登录随机码,否则返回""
	 */
	public static String parseLoginRandCode(String randCodeJson) {
		String result = "";
		if (randCodeJson != null && !"".equals(randCodeJson)) {
			/*
			 * 匹配是否为"randError":"Y",如果是"Y"则正确获取随机登录码
			 */
			String okPattern = ".*\"randError\"\\s*:\\s*\"Y\".*";
			if(randCodeJson.matches(okPattern)) {
				return ParseUtil.getValueFromJsonStr("loginRand", randCodeJson);
			}
		}
		return result;
	}
}
